package com.olap.starter.controller.admin.luckycola;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.olap.starter.util.HttpUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
@Log4j2
public class ChineseToEnglish {
    private final static String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    private final static String appid = "20240722002105668";
    private final static String key = "E66ZlOp6Fi86XTBugeVU";

    public static String toHexString(byte[] hash) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String getMD5(String input) {
        try {
            // 创建一个MessageDigest实例，初始化为MD5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            md.update(input.getBytes());
            // 完成哈希计算，得到结果
            byte[] digest = md.digest();
            // 将得到的字节转换成十六进制表示的字符串
            return toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public String getUnderline(String text) {
        String str = get(text);
        return parseConvertUnderline(str);
    }

    public String get(String text) {
        log.info("开始翻译[" + text + "]");
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();        // 不能使用HashMap，源码中会讲！
        map.add("fromlang", "ZH");
        map.add("tolang", "EN");
        map.add("text", text);
        StringBuilder params = new StringBuilder();
        long salt = System.currentTimeMillis();
        String k = appid + text + salt + key;
        log.info("key:" + k);
        String md5 = getMD5(k);
        log.info("md5:" + md5);
        /**
         *
         * tep1. 拼接字符串1：
         * 拼接appid=2015063000000001+q=apple+salt=1435660288+密钥=12345678得到字符串1：“2015063000000001apple143566028812345678”
         * Step2. 计算签名：（对字符串1做MD5加密）
         * sign=MD5(2015063000000001apple143566028812345678)，得到sign=f89f9594663708c1605f3d736d01d2d4
         *
         * 拼接完整请求：
         * http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
         *
         */
        try {
            text = URLEncoder.encode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String urls = url + "?q=" + text + "&from=zh&to=en&appid=" + appid + "&salt=" + salt + "&sign=" + md5;
        log.info(urls);
        try {

            String withCustomHeaders = HttpUtils.doGet(urls);
            log.info(salt + "MS耗时");
            log.info("返回数据：" + withCustomHeaders);

            JSONObject jsonObject = JSONObject.parseObject(withCustomHeaders);
            JSONArray o = (JSONArray) jsonObject.get("trans_result");
            JSONObject o1 = (JSONObject) o.get(0);
            return o1.get("dst").toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

    }

    public String parseConvertUnderline(String str) {
        str = str.replaceAll("[^a-zA-Z]+", "_").replaceAll("_+$", "").toLowerCase();
        return str;
    }
}
